package com.squirrel.common.interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.squirrel.common.annotation.AuthToken;
import com.squirrel.common.exception.MyAuthenticationException;
import com.squirrel.common.exception.BaseException;
import com.squirrel.common.response.code.CodeEnum;
import com.squirrel.common.service.UserService;
import com.squirrel.common.util.Audience;
import com.squirrel.common.util.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwt token验证拦截器
 *
 * @author olay
 * @version 1.0
 * @date 6/3/2021 11:37 PM
 */

@Slf4j
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws BaseException {

        /**
         * 测试阶段全部放行
         * @author 关远键
         * @date 2021/12/21 14:58

        // 忽略不带authToken注解的请求, 不做后续token认证校验
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            if (!handlerMethod.hasMethodAnnotation(AuthToken.class)) {
                return true;
            }
        }

        if (HttpMethod.OPTIONS.equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        // 获取请求头信息authorization信息
        final String authHeader = request.getHeader("JWT");
        log.info("## authHeader= {}", authHeader);
        log.info("request.path:" + request.getRequestURI());
        // 去掉前缀 modify by yuanjian 2021/11/27
        if (StringUtils.isBlank(authHeader)) {
            log.info("### 用户未登录，请先登录 ###");
            throw new MyAuthenticationException(CodeEnum.NO_AUTHORITY);
        }

        final String token = request.getHeader("JWT");
        log.info("token:{}", token);

        Audience audience = Audience.getInstance();

        log.info("----------------------------------断点调试---------------------------------");
        // 验证token是否有效--无效已做异常抛出，由全局异常处理后返回对应信息
        JwtTokenUtil.parseJWT(token, audience.getBase64Secret());

         */

        return true;
    }
}
